package com.rabbitmq.exec.ttl;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.exec.utils.RabbitMqUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lhj
 * @Date 2024/4/18 21:24
 */
public class Consumer01 {
    public static final String NORMAL_EXCHANGE_NAME = "normal_exchange";
    public static final String DEAD_EXCHANGE_NAME = "dead_exchange";
    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        channel.exchangeDeclare(NORMAL_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        
        String deadQueue = "dead-queue";
        //声名一个死信队列
        channel.queueDeclare(deadQueue, true, false, false, null);
        //死信队列绑定死信交换机
        channel.queueBind(deadQueue, DEAD_EXCHANGE_NAME, "lisi");
        

        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", "lisi");
//        arguments.put("x-max-length", 6);
//        arguments.put("x-dead-message-ttl", "10000");
        String normalQueue = "normal-queue";
        channel.queueDeclare(normalQueue, true, false, false, arguments);
        channel.queueBind(normalQueue, NORMAL_EXCHANGE_NAME, "zhangsan");

        System.out.println("消费者01 等待接收消息");
        DeliverCallback deliverCallback = ((consumerTag, message) -> {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            if ("info5".equals(msg)) {
                System.out.println(String.format("消费者01 接收到消息: %s 并拒绝该消息", msg));
                //requeue 设置为 false 代表拒绝重新入队 该队列如果配置了死信交换机将发送到死信队列中, 如果没有配置死信交换机则就行丢弃
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            }else {
                System.out.println(String.format("消费者01 接收到消息: %s queueName: %s exchangeName: %s", msg, normalQueue, NORMAL_EXCHANGE_NAME));
                /**
                 * multiple 表示批量应答
                 */
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        });
        boolean autoAck = false;
        channel.basicConsume(normalQueue, autoAck, deliverCallback, consumerTag -> {});
    }
    
}
